package org.example.hanlder.filter;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.constant.MessageConstant;
import org.example.constant.UserMessageConstant;
import org.example.dao.entity.Users;
import org.example.dto.req.UserRegisterReqDTO;
import org.example.exception.EmailExistException;
import org.example.exception.PhoneExistException;
import org.example.exception.UserNameExistException;
import org.example.service.UserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 用户之注册过滤器之验证参数是否正确
 */
@Component
public class UserRegisterParamVerifyChainFilter implements UserRegisterChainFilter<UserRegisterReqDTO>{

    @Resource
    private UserService userService;

    public UserRegisterParamVerifyChainFilter(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void handler(UserRegisterReqDTO reqDTO) {
        QueryWrapper<Users> qw = new QueryWrapper<>();
        qw.eq(UserMessageConstant.USER_NAME, reqDTO.getUserName());
        if (CollectionUtil.isNotEmpty(userService.list(qw))) {
            throw new UserNameExistException(MessageConstant.USERNAME_EXISTS);
        }

        QueryWrapper<Users> qw1 = new QueryWrapper<>();
        qw1.eq(UserMessageConstant.PHONE, reqDTO.getPhone());
        if (CollectionUtil.isNotEmpty(userService.list(qw1))) {
            throw new PhoneExistException(MessageConstant.PHONE_EXISTS);
        }

        QueryWrapper<Users> qw2 = new QueryWrapper<>();
        qw2.eq(UserMessageConstant.EMAIL, reqDTO.getEmail());
        if (CollectionUtil.isNotEmpty(userService.list(qw2))) {
            throw new EmailExistException(MessageConstant.EMAIL_EXISTS);
        }
    }

    @Override
    public int getOrder() {
        return 10;
    }
}
